package com.yoso.classload;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLClassLoader;

/**
 * @author shizejin
 * @date 2021/12/9
 * @description:
 */
public class MyClassLoader extends URLClassLoader {
//    private String rootDir = "file:/C:/Users/12425/Desktop/资料/";
    private String rootDir = "jar:file:/J:/database/Oracle/jar/ojdbc6.jar!/";

    public MyClassLoader() {
        super(new URL[0]);
    }

    /**
     * Finds and loads the class with the specified name from the URL search
     * file. Any URLs referring to JAR files are loaded and opened as needed
     * until the class is found.
     *
     * @param name the name of the class
     * @return the resulting class
     * @throws ClassNotFoundException if the class could not be found,
     *                                or if the loader is closed.
     * @throws NullPointerException   if {@code name} is {@code null}.
     */
    @Override
    protected Class<?> findClass(String name){
        String classPath = name.replace(".", "/").concat(".class");
        Class<?> aClass = null;
        try {
            URL url = new URL(rootDir+classPath);
            System.out.println(url.toString());
            InputStream inputStream = url.openStream();
            ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[1024];
            int n;
            while ((n=inputStream.read(bytes))!= -1){
                outputStream.write(bytes,0,n);
            }
            byte[] bytes1 = outputStream.toByteArray();
            aClass = defineClass(name,bytes1,0,bytes1.length);
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
        }
        return aClass;
    }

    @Override
    public Class<?> loadClass(String name) throws ClassNotFoundException {
        return super.loadClass(name);
    }
}

